---
name: useSize
route: /useSize
menu: 'Other'
edit: false
sidebar: true
---

import JackBox from 'jackbox';

import Demo1 from './demo/demo1';
import Demo1Tsx from '!raw-loader!./demo/demo1.tsx';
import Demo1Jsx from '!raw-loader!./demo/demo1.jsx';

import Demo2 from './demo/demo2';
import Demo2Tsx from '!raw-loader!./demo/demo2.tsx';
import Demo2Jsx from '!raw-loader!./demo/demo2.jsx';

import Demo3 from './demo/demo3';
import Demo3Tsx from '!raw-loader!./demo/demo3.tsx';
import Demo3Jsx from '!raw-loader!./demo/demo3.jsx';

# useSize

A hook to subscribe DOM element size change

## Examples

### Default usage

<JackBox tsCode={Demo1Tsx} jsCode={Demo1Jsx} demoName='Default usage' description='using ref to listen to size change'>
  <Demo1 />
</JackBox>

### Lazy load DOM element（used to subscibe to DOM element renders after the hook）

<JackBox tsCode={Demo2Tsx} jsCode={Demo2Jsx} demoName='Lazy load DOM element（used to subscibe to dom element renders after the hook）' description='pass in a function that returns the DOM element'>
  <Demo2 />
</JackBox>

### Listen to pre-rendered DOM

<JackBox tsCode={Demo3Tsx} jsCode={Demo3Jsx} demoName='Listen to pre-rendered DOM' description='pass in the DOM element itself'>
  <Demo3 />
</JackBox>

## API

```
const [ state, ref? ] = useSize(dom);
```

### Result

| Property | Description                                         | Type                 |
|----------|------------------------------------------|------------|
| state  | size and position of the DOM                             | { width: number, height: number }    |
| ref     | when no param is passed, this ref will be listened      | -        |

### Params

| Property | Description                                                        | Type                   | Default |
|---------|----------------------------------------------|------------------------|--------|
| dom? | optional, if none is passed, this hook will subscibe to the ref that it returns  | HTMLElement \| (() => HTMLElement) \| undefined | -      |